<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">商户后台管理系统</div>
    <div class="login-form-sub-title mb10">登录商户后台管理系统</div>
    <a-form ref="loginForm" :model="userInfo" class="login-form" layout="vertical" @submit="handleSubmit">
      <a-form-item field="username" :rules="[{ required: true, message: '请输入登录账号' }]" :validate-trigger="['change', 'blur']" hide-label>
        <a-input v-model="userInfo.username" :placeholder="'请输入登录账号'">
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item field="password" :rules="[{ required: true, message: '密码不能为空' }]" :validate-trigger="['change', 'blur']" hide-label>
        <a-input-password v-model="userInfo.password" placeholder="请输入密码" allow-clear>
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-form-item field="CaptchaCode" :rules="[{ required: true, message: '请输入验证码' }]" :validate-trigger="['change', 'blur']" hide-label>
        <a-input v-model="userInfo.CaptchaCode" placeholder="请输入验证码" allow-clear>
          <template #append>
            <img class="captcha" :src="captcha" @click="getCaptcha" />
          </template>
        </a-input>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox checked="rememberPassword" :model-value="loginConfig.rememberPassword" @change="setRememberPassword"> 记住密码 </a-checkbox>
          <a-button type="text" status="danger" size="small" @click="$emit('change')">忘记密码</a-button>
        </div>
        <a-button type="primary" html-type="submit" long :loading="loading"> 登录 </a-button>
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { message, get } from '@/utils'
import { ValidatedError } from '@arco-design/web-vue/es/form/interface'
import { useStorage } from '@vueuse/core'
import { useUserStore } from '@/store'
import useLoading from '@/hooks/loading'
const router = useRouter()
const route = useRoute()
const emit = defineEmits(['change'])

const { loading, setLoading } = useLoading()
const userStore = useUserStore()
const captcha = ref('')
const getCaptcha = () => {
  get({ url: '/server-auth/oauth/captcha' }, ({ data }) => {
    console.log(data)
    userInfo.CaptchaKey = data.key
    captcha.value = data.image
  })
}
getCaptcha()
const loginConfig = useStorage('login-config', {
  rememberPassword: true,
  username: '', // 演示默认值
  password: '', // demo default value
})
const userInfo = reactive({
  username: loginConfig.value.username,
  password: loginConfig.value.password,
  grant_type: 'captcha',
  tenantId: '000000',
  scope: 'all',
  type: 'account',
  CaptchaKey: '',
  CaptchaCode: '',
})

const handleSubmit = async ({ errors, values }: { errors: Record<string, ValidatedError> | undefined; values: Record<string, any> }) => {
  if (loading.value) return
  if (!errors) {
    setLoading(true)
    userStore.login(values, status => {
      if (status) {
        message({
          content: '欢迎使用',
          cb: () => {
            const { redirect, ...othersQuery } = router.currentRoute.value.query
            router.push({
              name: (redirect as string) || 'home',
              query: {
                ...othersQuery,
              },
            })
          },
        })
        const { rememberPassword } = loginConfig.value
        const { username, password } = values
        // 实际生产环境需要进行加密存储。
        // The actual production environment requires encrypted storage.
        loginConfig.value.username = rememberPassword ? username : ''
        loginConfig.value.password = rememberPassword ? password : ''
      }
      setLoading(false)
    })
  }
}
const setRememberPassword = (value: any) => {
  loginConfig.value.rememberPassword = value
}
</script>

<style lang="less" scoped>
.login-form {
  &-wrapper {
    width: 320px;
  }
  :deep(.arco-input-append) {
    padding: 0;
    .captcha {
      height: 4s0px;
    }
  }

  &-title {
    color: var(--color-text-1);
    font-weight: 500;
    font-size: 24px;
    line-height: 32px;
  }

  &-sub-title {
    color: var(--color-text-3);
    margin-bottom: 10px;
    font-size: 16px;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    color: rgb(var(--red-6));
    line-height: 32px;
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
  }

  &-register-btn {
    color: var(--color-text-3) !important;
  }
}
</style>
